#include "requestcombobox.h"

#include <QSqlTableModel>

RequestComboBox::RequestComboBox(QWidget *parent) :
    QComboBox(parent)
{
}

bool RequestComboBox::hasInDatabase()
{
    QSqlTableModel* model = qobject_cast<QSqlTableModel *>(this->model());
    if(!model) return false;
    QSqlTableModel* db_model = new QSqlTableModel(this);
    db_model->setTable(model->tableName());
    db_model->select();
    QModelIndexList items = db_model->match(model->index( 0, this->modelColumn()), Qt::DisplayRole, this->currentText(),  1, Qt::MatchExactly);
    return !items.isEmpty();
}

void RequestComboBox::setText(const QString &text)
{
    if(text.isEmpty()) return;
    QSqlTableModel* model = qobject_cast<QSqlTableModel *>(this->model());
    if(!model){
        this->setEditText(text);
        return;
    }
    QModelIndexList item = model->match(model->index( 0, this->modelColumn()), Qt::DisplayRole, text,  1, Qt::MatchExactly);
    if(!item.isEmpty()){
        this->setCurrentIndex(item[0].row());
    }
    else{
        this->setEditText(text);
    }
}

int RequestComboBox::itemModelId() const
{
    if(model()){
        QSqlTableModel *model = qobject_cast<QSqlTableModel *>(this->model());
        if(model){
            QString field("id");
            return model->data(model->index(currentIndex(), model->fieldIndex(field))).toInt();
        }
    }
    return -1;
}
